import pygame
import sys
import os
import pygame_gui

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from utils import get_chinese_font
from game.game_engine import GameEngine
from gui.game_window import GameWindow
from gui.main_menu import MainMenu

def main():
    """游戏主入口"""
    # 初始化pygame
    pygame.init()
    
    # 设置窗口大小
    width, height = 1024, 768
    window = pygame.display.set_mode((width, height))
    pygame.display.set_caption("三国杀")
    
    # 创建统一的UI管理器
    manager = pygame_gui.UIManager((width, height))
    
    # 创建时钟对象（放在主循环外，避免每次循环重新创建）
    clock = pygame.time.Clock()
    
    # 游戏主循环
    running = True
    game_state = "main_menu"  # main_menu, game_setup, playing, game_over
    game_engine = None
    game_window = None
    # 初始化主菜单（只传递window参数）
    main_menu = MainMenu(window)
    
    while running:
        # 计算时间增量
        time_delta = clock.tick(60) / 1000.0
        
        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            # 根据当前游戏状态处理事件
            if game_state == "main_menu":
                result = main_menu.handle_event(event)
                if result == "start_game":
                    # 进入游戏设置
                    game_state = "game_setup"
                    # 初始化游戏窗口
                    game_window = GameWindow(window, manager)
                elif result == "quit":
                    running = False
            
            elif game_state == "game_setup":
                if game_window:
                    result = game_window.handle_setup_event(event)
                    if result == "start_playing":
                        # 开始游戏
                        game_state = "playing"
                        # 根据选择的玩家数量调整角色列表
                        player_count = game_window.get_player_count()
                        game_engine = GameEngine()
                        # 只保留需要的角色数量
                        if len(game_engine.characters) > player_count:
                            game_engine.characters = game_engine.characters[:player_count]
                            # 确保第一个角色是人类玩家
                            if game_engine.characters:
                                game_engine.characters[0].is_human = True
                        game_engine.start_game()
            
            elif game_state == "playing":
                if game_window and game_engine:
                    result = game_window.handle_game_event(event, game_engine)
                    # 游戏逻辑更新
                    game_engine.update()
                    
                    # 检查游戏是否结束
                    if game_engine.is_game_over():
                        game_window.state = "game_over"
                        game_state = "game_over"
            
            elif game_state == "game_over":
                if game_window:
                    result = game_window.handle_game_over_event(event)
                    if result == "back_to_menu":
                        # 重置游戏状态
                        game_state = "main_menu"
                        game_engine = None
                        # 重新初始化主菜单
                        main_menu = MainMenu(window)
        
        # 渲染
        # 填充背景
        window.fill((139, 69, 19))
        
        # 根据游戏状态渲染对应界面
        if game_state == "main_menu":
            main_menu.render()
        elif game_state in ["game_setup", "playing", "game_over"]:
            if game_window:
                if game_state == "game_setup":
                    game_window.render(None)  # 游戏设置阶段不需要game_engine
                else:
                    game_window.render(game_engine)
        
        # 确保pygame_gui元素被正确渲染
        manager.draw_ui(window)
        
        # 更新pygame_gui管理器
        manager.update(time_delta)
        
        # 更新屏幕
        pygame.display.flip()
    
    # 退出游戏
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()